import { existsSync } from 'node:fs'
import { resolve, dirname } from 'node:path'
import { pathToFileURL } from 'node:url'

export interface Config {
  src: string
  out: string
  ext: string[]
  replace: { enable: boolean; fn: string; ext: string[] }
}

const DEFAULT: Config = {
  src: 'src',
  out: 'src/lang/zh-CN.json',
  ext: ['vue', 'js', 'jsx', 'ts', 'tsx'],
  replace: { enable: false, fn: '$t', ext: ['vue', 'js', 'jsx', 'ts', 'tsx'] },
}

                                            
export async function loadConfig(cwd = process.cwd()): Promise<Config> {
  let dir = cwd
  while (dir !== dirname(dir)) {
    const jsPath = resolve(dir, 'i18n.config.js')
    const jsonPath = resolve(dir, 'i18n.config.json')
    if (existsSync(jsPath))
      return (await import(pathToFileURL(jsPath).href)).default
    if (existsSync(jsonPath))
      return (await import(pathToFileURL(jsonPath).href)).default
    dir = dirname(dir)
  }
  return DEFAULT
}
